package by.ostrovsky.webhousingsystem.controller.wizard;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;

import by.ostrovsky.webhousingsystem.dao.DAOFactory;
import by.ostrovsky.webhousingsystem.dao.implementation.WizardTransactor;
import by.ostrovsky.webhousingsystem.dao.implementation.idao.IWizardDAO;
import by.ostrovsky.webhousingsystem.exception.OperationErrorException;
import by.ostrovsky.webhousingsystem.hibernate.entity.Employee;
import by.ostrovsky.webhousingsystem.hibernate.entity.TaskGroup;
import by.ostrovsky.webhousingsystem.hibernate.entity.UserRequest;
import by.ostrovsky.webhousingsystem.hibernate.entity.WorkPlan;

public class WizardController {
	private static Logger logger = Logger.getLogger(WizardController.class);

	@SuppressWarnings("unchecked")
	public void save(Map<String, Object> map) throws OperationErrorException {
		try {
			DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.MySQL);

			WizardTransactor transactor = new WizardTransactor();
			transactor.begin();
			
			IWizardDAO<TaskGroup> tgDao = factory.getTaskGroupWizardDAO(transactor);
			IWizardDAO<Employee> emDao = factory.getEmployeeWizardDAO(transactor);
			IWizardDAO<WorkPlan> wpDao = factory.getWorkPlanWizardDAO(transactor);
			IWizardDAO<UserRequest> hrDao = factory.getHousingRequestWizardDAO(transactor);
			
			try {
				tgDao.save((TaskGroup) map.get("tg"));
				emDao.update((List<Employee>) map.get("em"));
				wpDao.save((WorkPlan) map.get("wp"));
				
				UserRequest ur = (UserRequest) map.get("hr");
				ur.setAccepted(true);
				
				hrDao.update(ur);
				
			} catch (HibernateException e) {
				transactor.rollback();
				transactor.close();
				logger.error(e);
				throw new OperationErrorException();
			}
			
			transactor.commit();
			transactor.close();
		} catch (Exception e) {
			logger.error(e);
			throw new OperationErrorException();
		}
	}
}
